import https from "https";
import { Buffer } from "node:buffer";
import fs from "fs";
import access_token from "./access_token.js";
import { fileURLToPath } from "url";
import path from "path";

// 获取绝对路径
const getRootPath = (pathUrl) => {
  // esm 模块没有 CommonJS的 __dirname
  // 这里需要通过工具函数fileURLToPath来封装一个 __dirname
  // 注意：这里的 __dirname 指向的是当前文件 utils/index.js 的路径，因此加了一层 ../ 来将路径修改到 bin目录
  const __dirname = fileURLToPath(import.meta.url);
  return path.resolve(__dirname, `../${pathUrl}`);
};

// 根据 open api 读取远程仓库内容，并写入本地 https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoContents(Path)
const getGitRemoteFileAndWrite = (path, dirPath) => {
  return new Promise((resolve) => {
    const owner = "yanhuakang";
    const repo = "create-package-tools-template";
    let req = https.get(
      `https://gitee.com/api/v5/repos/${owner}/${repo}/contents/${path}?access_token=${access_token}`,
      (res) => {
        let data = "";
        res.on("data", (chunk) => {
          data += chunk;
        });
        res.on("end", async () => {
          await writeFile(JSON.parse(data), dirPath);
          resolve();
        });
      }
    );
    req.end();
  });
};

// 位图 ext
const extArr = ["png", "jpeg", "jpg", "ico", "gif"];

// 获取文件内容，写入文件
const writeFile = async (result, dirPath) => {
  if (Array.isArray(result)) {
    // 目录
    for (const item of result) {
      if (item.type === "dir") {
        // 如果是文件夹，则先创建文件夹
        fs.mkdirSync(getRootPath(item.path), { recursive: true });
      }
      if (item.type === "dir" || (item.type === "file" && !item.size)) {
        // 递归获取远程仓库文件
        await getGitRemoteFileAndWrite(item.path);
      }
    }
  } else {
    // 文件
    let contentUtf8 = "";
    if (result.encoding === "base64") {
      const bufferContent = Buffer.from(result.content, "base64");
      const nameSplit = result.name.split(".");
      const ext = nameSplit[nameSplit.length - 1];
      // 一些位图需要写入 buffer
      if (extArr.includes(ext)) {
        contentUtf8 = bufferContent;
      } else {
        // 文件或矢量图写入 utf8
        contentUtf8 = bufferContent.toString("utf8");
      }
    }
    fs.writeFile(
      getRootPath(`${dirPath ? dirPath : "."}/${result.path}`),
      contentUtf8,
      { encoding: "utf8" },
      (err) => {
        if (err) {
          throw err;
        }
      }
    );
  }
};

export default getGitRemoteFileAndWrite;
